package top.cardone.security.shiro.web.filter.authc.impl;

import lombok.Setter;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.CharEncoding;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import top.cardone.context.util.CodeExceptionUtils;
import top.cardone.security.shiro.authc.impl.StatelessTokenImpl;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Writer;

/**
 * Created by yht on 16-2-2.
 */
@Log4j2
public class StatelessAuthcFilterImpl extends AuthenticatingFilter {
    @Setter
    protected String credentialsParam = "token";

    @Override
    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
        String credentials = request.getParameter(credentialsParam);

        if (StringUtils.isBlank(credentials)) {
            HttpServletRequest httpRequest = (HttpServletRequest) request;

            credentials = httpRequest.getHeader(credentialsParam);
        }

        StatelessTokenImpl token = new StatelessTokenImpl();

        token.setCredentials(credentials);

        return token;
    }


    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        Subject subject = getSubject(request, response);

        if (!subject.isAuthenticated()) {
            return executeLogin(request, response);
        }

        return true;
    }

    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        if (!org.apache.commons.lang3.StringUtils.startsWith(request.getContentType(), org.springframework.http.MediaType.APPLICATION_JSON_VALUE)) {
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

            return false;
        }

        response.setCharacterEncoding(CharEncoding.UTF_8);
        response.setContentType(org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE);

        try (Writer out = response.getWriter()) {
            String requestURI = getPathWithinApplication(request);

            String json = CodeExceptionUtils.newString(requestURI, e);

            out.write(json);

            out.flush();
        } catch (java.io.IOException ex) {
            log.error(ex.getMessage(), ex);
        }

        return false;
    }
}